<template>
  <el-row :gutter="20" class="app-container">
    <Splitpanes>
      <pane size="16" v-if="$auth.hasRoleOr(['admin','manager','fishingceo'])">
        <el-col>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
      </pane>
      <pane :size="$auth.hasRoleOr(['admin','manager','fishingceo']) ? 84 : 100">
        <!-- <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="鱼塘" prop="pondId">
            <el-select
              v-model="queryParams.pondId"
              @change="handleQuery"
              placeholder="选择鱼塘"
              style="width: 120px"
            >
              <el-option
                v-for="item in pondOptionList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form> -->

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['pond:seat:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['pond:seat:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['pond:seat:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['pond:seat:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="seatList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="钓位ID" align="center" prop="id" />
          <el-table-column label="所属钓场" align="center" prop="deptName" />
          <el-table-column label="所属鱼塘" align="center" prop="pondName" />
          <el-table-column label="钓位编号" align="center" prop="code" />
          <el-table-column label="钓位价格" align="center" prop="price" />
          <el-table-column label="是否可预约" align="center" prop="reservable">
            <template #default="scope">
              <span>{{ scope.row.reservable == 0 ? "否" : "是" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['pond:seat:edit']"
                >修改</el-button
              >
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['pond:seat:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改钓位信息对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
          <el-form
            ref="seatRef"
            :model="form"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="所属钓场" prop="deptId">
              <DeptSelect
                v-model="form.deptId"
                @change="handleDeptChange"
              />
            </el-form-item>
            <el-form-item label="是否批量新增" prop="isBatch">
              <el-radio-group v-model="form.isBatch">
                <el-radio :label="false">否</el-radio>
                <el-radio :label="true">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <template v-if="form.isBatch">
              <el-form-item label="批量新增数量" prop="batchCount">
                <el-input
                  v-model="form.batchCount"
                  placeholder="请输入数量"
                  @input="handleBatchCountInput"
                  maxlength="3"
                />
              </el-form-item>
              <el-form-item label="钓位名称" prop="codePrefix">
                <el-input
                  v-model="form.codePrefix"
                  placeholder="请输入钓位名称"
                >
                  <template #append>
                    <el-popover placement="top" :width="300" trigger="hover">
                      <template #reference>
                        <el-icon><Warning /></el-icon>
                      </template>
                      <div>
                        <p>命名规则说明：</p>
                        <p>输入名称后会自动添加序号</p>
                        <p>例如：双人台 -> 双人台01..双人台02</p>
                      </div>
                    </el-popover>
                  </template>
                </el-input>
              </el-form-item>
            </template>
            <el-form-item label="所属鱼塘" prop="pondId">
              <PondSelect
                v-model="form.pondId"
                :dept-id="form.deptId"
                @change="handlePondChange"
              />
            </el-form-item>
            <el-form-item label="钓位编号" prop="code" v-if="!form.isBatch">
              <el-input v-model="form.code" placeholder="请输入钓位编号" />
            </el-form-item>
            <el-form-item label="钓位状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择钓位状态">
                <el-option label="空闲" :value="0" />
                <el-option label="使用中" :value="1" />
                <el-option label="维护中" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="钓位价格" prop="priceSegmentId">
              <el-select
                v-model="form.priceSegmentId"
                placeholder="请选择价格段"
                style="width: 100%"
                :disabled="!selectedPond || !selectedPond.priceSegments || selectedPond.priceSegments.length === 0"
              >
                <el-option
                  v-for="segment in (selectedPond?.priceSegments || [])"
                  :key="segment.id"
                  :label="formatPriceSegmentLabel(segment)"
                  :value="segment.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否可预约" prop="reservable">
              <el-select
                v-model="form.reservable"
                placeholder="请选择是否可预约"
              >
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </pane>
    </Splitpanes>
  </el-row>
</template>

<script setup name="PondSeat">
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { useDeptTree } from "@/utils/deptTreeUtils";
import { listPond } from "@/api/pond/pond";
import PondSelect from "@/components/PondSelect/index.vue";
import DeptSelect from "@/components/DeptSelect/index.vue";
import {
  listSeat,
  getSeat,
  delSeat,
  addSeat,
  updateSeat,
} from "@/api/pond/seat";
import { Warning } from "@element-plus/icons-vue";

const { proxy } = getCurrentInstance();

const seatList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 使用部门树工具
const {
  deptOptions,
  enabledDeptOptions,
  getDeptTree,
  handleFormDeptNodeClick,
  handleSidebarDeptNodeClick,
} = useDeptTree();
const pondOptionList = ref([]);
const formPondOptionList = ref([]);
const selectedPond = ref(null);

// 钓位状态选项
const statusOptions = ref([
  { value: 0, label: "空闲" },
  { value: 1, label: "使用中" },
  { value: 2, label: "维护中" },
]);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pondId: null,
    deptId: undefined,
    code: null,
    status: null,
    price: null,
    reservable: null,
  },
  rules: {
    pondId: [{ required: true, message: "所属鱼塘不能为空", trigger: "blur" }],
    deptId: [{ required: true, message: "所属钓场不能为空", trigger: "blur" }],
    code: [{ required: true, message: "钓位编号不能为空", trigger: "blur" }],
    priceSegmentId: [{ required: true, message: "钓位价格不能为空", trigger: "change" }],
    batchCount: [
      { required: true, message: "批量新增数量不能为空", trigger: "blur" },
    ],
    codePrefix: [
      { required: true, message: "钓位名称前缀不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 表单中的部门树节点点击事件 */
function handleFormDeptNodeClickLocal(data, node, e) {
  handleFormDeptNodeClick(data, node, e, (deptId) => {
    form.value.deptId = deptId;
    // 当部门改变时，重新加载对应的鱼塘列表
    if (deptId) {
      const params = {
        pageNum: 1,
        pageSize: 10,
        deptId: deptId,
      };
      listPond(params).then((response) => {
        formPondOptionList.value = response.rows || [];
        form.value.pondId = null; // 清空鱼塘选择
      });
    } else {
      formPondOptionList.value = [];
      form.value.pondId = null;
    }
  }, proxy, 'deptTreeSelectRef');
}

/** 侧边栏部门树节点单击事件 */
function handleNodeClick(data) {
  handleSidebarDeptNodeClick(data, (deptId) => {
    queryParams.value.deptId = deptId;
    handleQuery();
  });
}

/** 获取鱼塘选项 */
function getOptions() {
  const params = {
    pageNum: 1,
    pageSize: 10,
    deptId: queryParams.value.deptId,
  };
  listPond(params).then((response) => {
    pondOptionList.value = response || [];
  });
}

/** 查询钓位信息列表 */
function getList() {
  loading.value = true;
  listSeat(queryParams.value).then((response) => {
    seatList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    pondId: null,
    deptId: null,
    code: null,
    status: 0,
    priceSegmentId: null,
    coordinate: null,
    reservable: 1,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    isBatch: false,
    batchCount: 1,
    codePrefix: "",
  };
  selectedPond.value = null;
  proxy.resetForm("seatRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  proxy.$refs.deptTreeRef && proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 设置默认部门为左侧树选中的部门
  form.value.deptId = queryParams.value.deptId;
  // 如果有选中的部门，获取对应的鱼塘列表
  if (form.value.deptId) {
    const params = {
      pageNum: 1,
      pageSize: 10,
      deptId: form.value.deptId,
    };
    listPond(params).then((response) => {
      formPondOptionList.value = response.rows || [];
    });
  }
  open.value = true;
  title.value = "添加钓位信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getSeat(_id).then((response) => {
    form.value = response.data;
    
    // 如果有部门ID，加载对应的鱼塘列表
    if (form.value.deptId) {
      const params = {
        pageNum: 1,
        pageSize: 10,
        deptId: form.value.deptId,
      };
      listPond(params).then((pondResponse) => {
        formPondOptionList.value = pondResponse.rows || [];
        // 设置选中的鱼塘
        if (form.value.pondId) {
          selectedPond.value = formPondOptionList.value.find(pond => pond.id === form.value.pondId);
        }
      });
    }
    
    open.value = true;
    title.value = "修改钓位信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["seatRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
          updateSeat({...form.value,batchCount:+form.value.batchCount}).then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addSeat({...form.value,batchCount:+form.value.batchCount}).then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除钓位信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delSeat(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "pond/seat/export",
    {
      ...queryParams.value,
    },
    `seat_${new Date().getTime()}.xlsx`
  );
}

/** 部门树节点点击事件 */
function handleDeptNodeClick(data, node, e) {
  // 如果是最后一级部门，则选中
  if (!data.children || data.children.length === 0) {
    form.value.deptId = data.id;
    handleDeptChange(data.id);
  } else {
    // 如果不是最后一级，则展开/折叠节点，并阻止下拉框关闭
    node.expanded = !node.expanded;
    e.stopPropagation();
    // 阻止下拉框关闭
    proxy.$nextTick(() => {
      proxy.$refs.deptTreeSelectRef.focus();
    });
  }
}

/** 所属钓场选择变化事件 */
function handleDeptChange(deptId) {
  if (deptId) {
    const params = {
      pageNum: 1,
      pageSize: 10,
      deptId: deptId,
    };
    listPond(params).then((response) => {
      formPondOptionList.value = response.rows || [];
      console.log(formPondOptionList.value, " formPondOptionList.value");
      // 清空已选择的鱼塘
      form.value.pondId = null;
    });
  } else {
    formPondOptionList.value = [];
    form.value.pondId = null;
  }
}

// 监听部门选择变化
watch(
  () => queryParams.value.deptId,
  (newVal) => {
    if (newVal) {
      getOptions();
    } else {
      pondOptionList.value = [];
    }
  }
);


/** 批量新增数量输入处理 */
function handleBatchCountInput(value) {
  // 只允许输入数字
  form.value.batchCount = value.replace(/[^\d]/g, "");
  // 限制最大值为100
  if (form.value.batchCount > 100) {
    form.value.batchCount = 100;
  }
}

/** 鱼塘选择变化事件 */
function handlePondChange(pondId) {
  if (pondId) {
    // 找到选中的鱼塘
    selectedPond.value = formPondOptionList.value.find(pond => pond.id === pondId);
    // 清空已选择的价格段
    form.value.priceSegmentId = null;
  } else {
    selectedPond.value = null;
    form.value.priceSegmentId = null;
  }
}

/** 格式化价格段标签 */
function formatPriceSegmentLabel(segment) {
  let label = `价格：${segment.price}元，时长：${segment.durationHours}小时`;
  if (segment.returnPrice) {
    label += `，回鱼价格：${segment.returnPrice}元/斤`;
  }
  return label;
}

getDeptTree();
getOptions();
getList();
</script>
